<template>
  <div class="login-container">
    <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-position="left" label-width="0px" class="login-form">
      <h2 style="align-items: center;">修改密码</h2>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="新密码"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="mail" v-model="registerForm.confirmPassword" placeholder="确认密码"></el-input>
      </el-form-item>
      <div class="bottom-div">
          <el-button class="bottom-div-button" style="margin:0;" type="primary" color="black" @click="handleRegister">确认</el-button>
          <el-button class="bottom-div-button" style="margin:0;" type="primary" color="black" @click="this.$router.push(`/login`)">返回登录页面</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      registerRules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: this.validatePasswordConfirmation, trigger: 'blur' }
        ]
      },
      value1: ''
    };
  },
  methods: {
    validatePasswordConfirmation(rule, value, callback) {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致!'));
      } else {
        callback();
      }
    },
    async handleRegister() {
      const flag = this.validate();
      if (flag) {
        const res = await axios.put('/api/userT/updatePassword', {
          id: localStorage.getItem('id'),
          password: this.registerForm.password
        }, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        if (res.data.code === 1) {
          window.alert("修改成功");
          this.$router.push('/login')
        } else {
          ElMessage.error(res.data.msg)
        }
      }
    },
    validate() {
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        return false;
      }
      return true;
    }
  }
};
</script>

<style >
.login-container {
  flex-direction: row;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background: rgba(0, 0, 0, 0);
}


.login-form {
  /* flex-direction: row; */
  /* display: flex; */
  width: 50%; /* 根据需要调整宽度 */
  /* max-width: 300px; 设置最大宽度以防止过大屏幕下表单过宽 */
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>